<?php

/**
 * Created by PhpStorm.
 * User: 申霖
 * Date: 2019/9/1 0001
 * Time: 上午 8:57
 */
class Api extends CI_Controller
{
    /**
     * 外部接口
     * @author 申霖
     * @time 2019/9/1 0001 上午 8:59
     */
    public function home()
    {
        //读取配置，未配置则要求配置
        $this->config->load('sevenOxen');
        $ak     = $this->config->item('ak');
        $sk     = $this->config->item('sk');
        $bucket = $this->config->item('bucket');
        $domain = $this->config->item('domain');
        if (!$ak or !$sk or !$bucket or !$domain) {
            echo json_encode(array('code' => 100, 'message' => '配置信息错误'));
        }
        //使用缓存
        $this->load->driver('cache');
        $serverList = $this->cache->get('serverList');
        if (!$serverList) {
            $serverList = $this->data($ak, $sk, $bucket, $domain);
            $this->cache->save('serverList', $serverList, 300);
        }
        echo json_encode(array('code' => 200, 'message' => '配置信息错误', 'data' => $serverList));
    }

    /**
     * 获取资源列表
     * @param $ak
     * @param $sk
     * @param $bucket
     * @param $domain
     * @return mixed
     * @author 申霖
     * @time 2019/8/27 0027 下午 9:29
     */
    public function data($ak, $sk, $bucket, $domain)
    {
        $this->load->library("Qiniu");
        // 构建鉴权对象
        $auth = new Qiniu\Auth($ak, $sk);
        // 配置
        $config = new \Qiniu\Config();
        // 管理资源
        $bucketManager = new \Qiniu\Storage\BucketManager($auth, $config);
        // 获取空间名称
        $res  = $bucketManager->listFiles($bucket);
        $info = $res[0]['items'];
        $this->load->helper('common');
        $data = array();
        foreach ($info as $k => $v) {
            $data[$k]['trackName']   = $v['key'];
            $data[$k]['file']        = $domain . '/' . $v['key'];
            $data[$k]['thumb']       = 'http://static.shenlin.ink/bj.jpg';
            $data[$k]['trackArtist'] = $data[$k]['trackAlbum'] = '未知';
        }
        array_pop($data);
        return $data;
    }
}
